package com.wr.CompletableFutureDemo12;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 异步回调
 */
public class CompletableFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "supplyAsync");
//            int i = 10 / 0;
            return 1024;
        }).thenApplyAsync((i)->{
//            System.out.println(i);  // 1024
            return i/2;
        }).whenComplete((t, u) -> {
            System.out.println("t=" + t);  // 程序正确返回return的值，否则返回null
            System.out.println("u=" + u);  // 有异常就返回异常信息，否则返回null
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 0;
        });
        System.out.println(integerCompletableFuture.get());

//        integerCompletableFuture.thenApplyAsync((i)->{
////            System.out.println(i);  // 1024
//            return i/2;});


        // 是supplyAsync成功返回的信息
        // t-->成功信息    u-->失败信息
//        CompletableFuture<Integer> exceptionally = integerCompletableFuture.whenComplete((t, u) -> {
//            System.out.println("t=" + t);
//            System.out.println("u=" + u);
//        }).exceptionally((e) -> {
//            e.getMessage();
//            return 0;
//        });
//
//        try {
//            System.out.println(exceptionally.get());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
    }
}
